import QtQuick 1.1
import QtWebKit 1.0
import Qt 4.7
import "js/dbmanager.js" as DB


Item {
    id: snaprOAuth
    property string nextState: "AuthDone"
    property string clientId: "20bb9990fdd85931274ffaa8feb72c5e"
    property string clientSecret: "b1ec69a08931433bac322436a9986b81"
    anchors.fill: parent
    Component.onCompleted: DB.checkToken()
    property string token: ""
    WebView {
        id: loginView
        visible: false
        anchors.fill: parent
        onUrlChanged: changeUrl(url)
    }

    states: [
        State {
            name: DB.STATES.LOGIN
            PropertyChanges {
                target: loginView
                visible: true
                url: "http://sna.pr/ext/oauth/authorize/"+
                     "?redirect_uri=http://sna.pr&client_id=" + clientId +"&response_type=code"
            }
        },
        State {
            name: DB.STATES.AUTHDONE
            PropertyChanges {
                target: loginView
                visible: false
                opacity: 0
            }
            PropertyChanges {
                target: parent
                state: nextState
            }
        }
    ]

    function changeUrl(url) {
        var authorized = false;
        var mUrl = url.toString();
        var code = "";
        if (mUrl.indexOf("http://sna.pr") > -1) {
            var query = mUrl.substring(mUrl.indexOf('?') + 1);
            var vars = query.split("&");
            for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if (pair[0] == "code") {
                    authorized = true;
                    code = pair[1];
                    if(debug) console.log("code: " + code);
                }
            }
        }
        if (authorized) {
            requestPermanentToken(code);
        }
    }


    function requestPermanentToken(code) {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                var result = eval('(' + req.responseText + ')');
                if (result.error === null) {
                    token = result.access_token
                }
            }
        }
        req.open("POST", "https://sna.pr/ext/oauth/access_token/", true);
        req.send("grant_type=authorization_code"+
                 "&client_id=" +clientId +
                 "&client_secret=" + clientSecret +
                 "&code=" + code + "&redirect_uri=http://sna.pr");

        DB.saveToken(token);
    }
}

